package com.sailfish.springbootdemo.configs;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 数据源 4 配置，假如是 mysql
 */
@Configuration(value = "db4")
@MapperScan(basePackages = "com.sailfish.springbootdemo.dao.db4", sqlSessionFactoryRef = "MysqlSqlSessionFactory4")
public class MySQL4Config {
    @Bean(name = "MysqlDataSource4")
    @ConfigurationProperties(prefix = "spring.datasource.db4")
    public DataSource getDateSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 配置事务管理
     */
    @Bean(name = "MysqlTransactionManager4")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("MysqlDataSource4") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 配置工厂
     *
     * @param datasource
     * @return
     * @throws Exception
     */
    @Bean(name = "MysqlSqlSessionFactory4")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("MysqlDataSource4") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        //bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/mysql/*.xml"));
        return bean.getObject();
    }

    /**
     * 配置会话
     *
     * @param sessionfactory
     * @return
     */
    @Bean("MysqlSqlSessionTemplate4")
    public SqlSessionTemplate testsqlsessiontemplate(
            @Qualifier("MysqlSqlSessionFactory4") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
}
